#include "common.h"
#include "texture.h"
#include "tga.h"

bool TextMan::Get( const std::string& name, unsigned int *id )
{
	assert( id );
	Textures::iterator it = textures.find( name );
	if ( it == textures.end() ) {
		// successful load
		if ( Load( name, id) ) {
			textures[ name ] = *id;
		} else {
			return false;
		}
	} else {
		*id = textures[ name ] ;
	}
	return true;
}

bool TextMan::Load( const std::string& name, unsigned int *id )
{
	assert( id );	
	GLint iWidth, iHeight, iComponents;
	GLenum eFormat;	
	// generates texture id
	glGenTextures( 1, static_cast<GLuint*>( id ) );
	// complete path to texture
	std::string completePath = path + "\\" + name;	    		
	// load tga texture
	GLbyte *pBytes = gltLoadTGA( completePath.c_str(), &iWidth, &iHeight, &iComponents, &eFormat );
	// can't load texture
	if ( !pBytes )
		return false;
	// bind texture with id
	glBindTexture( GL_TEXTURE_2D, *id );
	// build texture
	glTexImage2D( GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBytes );
	// free now
	free( pBytes );
	// set filters    
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	// success
	return true;
}
